#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>

const int tdnum = 6;
// 1. 多线程创建
// 2. 线程传参和返回值，我们可以传递级别信息，也可以传递其他对象(包括你自己定义的！)

class Task
{
public:
	Task()
	{
	}
	~Task()
	{
	}

	void SetData(int x, int y)
	{
		datax = x;
		datay = y;
	}

	int Excute()
	{
		return datax + datay;
	}

private:
	int datax;
	int datay;
};

class ThreadData
{
public:
	ThreadData(int x, int y, const std::string &name) : _threadname(name)
	{
		_t.SetData(x, y);
	}

	std::string threadname()
	{
		return _threadname;
	}

	int run()
	{
		return _t.Excute();
	}

private:
	std::string _threadname;
	Task _t;
};

class result
{
public:
	result() {}
	~result() {}

	void Setresult(int result, const std::string &threadname)
	{
		_result = result;
		_threadname = threadname;
	}

	void Print()
	{
		std::cout << _threadname << ":" << _result<<std::endl;
	}

private:
	int _result;
	std::string _threadname;
};

void *handler(void *args)
{
	ThreadData *td = static_cast<ThreadData*>(args);
	std::string name = td->threadname();

	result* ret = new result();
	int result = td->run();

	ret->Setresult(result,name);

	delete td;

	sleep(1);
	return ret;
}

int main()
{
	std::vector<pthread_t> tds;
	for (int i = 0; i < tdnum; i++)
	{
		char threadname[64];
		snprintf(threadname , 64,"Thread-%d",i+1);
		ThreadData* td = new ThreadData(10,20,threadname);

		pthread_t tid;
		pthread_create(&tid, nullptr, handler, td);
		tds.push_back(tid);
		sleep(1);
	}

	std::vector<result*> result_set;
	void* ret = nullptr;

	for (auto &tid : tds)
	{
		pthread_join(tid, &ret);
		result_set.push_back((result*)ret);
	}

	for(auto & res : result_set)
    {
        res->Print();
        delete res;
    }
	return 0;
}